package com.zzyl.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.Random;

@Configuration
public class SpringCacheConfig {

    @Bean
    public RedisCacheManager cacheManagerOneDay(RedisConnectionFactory connectionFactory) {
        int randomNum = new Random().nextInt();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                //过期时间为基础时间加随机时间
                .entryTtl(Duration.ofSeconds(24 * 60 * 60L * randomNum))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }
}
